package com.hy.utils.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

@WebFilter(value = "/*", filterName = "DirtyWordsFilter")
public class DirtyWordsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        DirtyWordsHttpServletRequest drequest = new DirtyWordsHttpServletRequest(request);

        chain.doFilter(drequest, response);
    }

    @Override
    public void destroy() {

    }

    private class DirtyWordsHttpServletRequest extends HttpServletRequestWrapper {

        public List<String> file() throws IOException {
            ServletContext context = getServletContext();

            String filePath = context.getRealPath("/file/swearing.txt");
            File file = new File(filePath);

            InputStream fis = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(fis,"UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String line = br.readLine();
            List<String> values = new ArrayList<>();

            if (line != null) {
                String[] tokens = line.split(",");
                for (String token : tokens) {
                    values.add(token.trim());
                }
            }
            br.close();
            return values;
        }

        public DirtyWordsHttpServletRequest(HttpServletRequest request) throws IOException {
            super(request);
        }

        @Override
        public String getParameter(String name) {
           /* System.out.println("patfff");*/
            String content = super.getParameter(name);
            List<String> dirtysWords = new ArrayList<>();
            try {
                dirtysWords = this.file();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (content == null)
                return null;
            for (String dirtyWord : dirtysWords) {
                if (content.contains(dirtyWord))
                    content = content.replace(dirtyWord, "**");
            }

            return content;
        }
    }
}
